import React, { useEffect, useState, useMemo, useRef } from 'react';
import {
  Card,
  Form,
  Input,
  Upload,
  message,
  Divider,
  Button,
  Modal,
  DatePicker,
  Select,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import WineLogo from '../../../assets/img/ExhibitorInfo/WineLogo.jpg';
import styles from './index.less';
import ShowInfo from '../../components/ShowInfo';
import Config from '../../../config/Config';
import { connect, routerRedux } from 'dva';
import moment from 'moment';
import E from '../../../../../contants/E';
import { FormattedMessage } from 'umi';

const formItemLayout = {
  labelCol: { xxl: { span: 24 }, xl: { span: 24 } },
  wrapperCol: { xxl: { span: 24 }, xl: { span: 24 } },
};
const inputStyle = { width: 450 };

function WineEdit({ dispatch, wineInfo, match, currentUser, submitLoding }) {
  const form = useRef();

  const [imageUrl, setImageUrl] = useState();
  const [pictures, setPictures] = useState();
  const [showModal, setShowModal] = useState(false);
  const [userId, setUserId] = useState(null);
  const [checkNickNameEn, setCheckNickNameEn] = useState(true);
  const [checkNickNameCn, setCheckNickNameCn] = useState(true);

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  // const getBase64 = (img, callback) => {
  //   const reader = new FileReader();
  //   reader.addEventListener('load', () => callback(reader.result));
  //   reader.readAsDataURL(img);
  // };

  useEffect(() => {
    if (match.params.id == '0') {
      return;
    }
    const id = match.params.id;
    dispatch({ type: 'wineInfo/apiGetWine', payload: { id } });
    setUserId(match.params.id);
  }, []);

  useEffect(() => {
    return () => {
      dispatch({ type: 'wineInfo/setState', payload: { wineInfo: null } });
    };
  }, []);

  useEffect(() => {
    if (userId && userId !== '0') {
      const {
        current: { setFieldsValue },
      } = form;

      if (wineInfo) {
        // wineInfo && (wineInfo.vintage = moment(wineInfo.vintage, 'YYYY-MM-DD'));
        wineInfo.type = `${wineInfo.type}/${wineInfo.typeEn}`;
        wineInfo.region = `${wineInfo.region}/${wineInfo.regionEn}`;
        wineInfo && delete wineInfo.updatedAt;
        // console.log(wineInfo, wineInfo.vintage, 'alcohol');
        setFieldsValue({ ...wineInfo });
        setImageUrl(wineInfo.wineLabelUrl);
        wineInfo.wineLabelUrl &&
          setPictures([
            {
              uid: wineInfo.id,
              name: wineInfo.wineLabelUrl,
              status: 'done',
              url: wineInfo.wineLabelUrl,
              response: { file: wineInfo.logoUrl, url: wineInfo.wineLabelUrl },
            },
          ]);
      }
    }
  }, [wineInfo]);

  const handleChange = (info) => {
    setPictures(info.fileList);
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      // getBase64(info.file.originFileObj, (imageUrl) => {
      //   setImageUrl(imageUrl);
      // });
      const data = info.file.response;
      setImageUrl(data.url);
    }
  };
  const handlePreview = async (file) => {
    setShowModal(true);
  };
  // const beforeUpload = (file) => {
  //   const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  //   if (!isJpgOrPng) {
  //     message.error('You can only upload JPG/PNG file!');
  //   }
  //   const isLt2M = file.size / 1024 / 1024 < 2;
  //   if (!isLt2M) {
  //     message.error('Image must smaller than 2MB!');
  //   }
  //   return isJpgOrPng && isLt2M;
  // };

  const onFinish = (value) => {
    const id = match.params.id;
    const vintage = moment(value.vintage).format('YYYY');
    const [region, regionEn] = value.region.split('/');
    const [type, typeEn] = value.type.split('/');
    value.vintage = vintage;
    value.wineLabelUrl = imageUrl;
    value.annualOutput = value.annualOutput;
    value.exhibitorID = currentUser.exhibitorID;
    value.alcohol = value.alcohol;
    value.regionEn = regionEn;
    value.region = region;
    value.type = type;
    value.typeEn = typeEn;

    // value.regionEn

    // console.log(value, 'value');
    // console.log(currentUser, 'currentUser');
    if (id && id === '0') {
      dispatch({ type: 'wineInfo/setState', payload: { submitLoding: true } });
      dispatch({ type: 'wineInfo/apiPostWine', payload: { ...value } });
    } else {
      value.id = id;
      dispatch({ type: 'wineInfo/setState', payload: { submitLoding: true } });
      dispatch({ type: 'wineInfo/apiPutWine', payload: { ...value } });
    }

    dispatch(routerRedux.push(`/wineInfo/WineInfoList`));
  };
  const modalOnCancel = () => {
    setShowModal(false);
  };
  const onFinishFailed = (values) => {
    // console.log(values, err);
    if (values.errorFields.length > 0) {
      message.error('请检查必填项是否填写');
    }
  };

  const showInfoData = {
    title: '酒品图片上传规范及标准',
    img: WineLogo,
    textList: [
      '上传的酒品图片需整洁、清晰，并以白底或透明底为佳',
      '图片的宽高比为1:1，尺寸控制为500*500px为最佳',
      '图片格式仅支持JPG、PNG',
      '为保证贵商的酒品展示效果最佳，建议酒品图片实际高度控制在460,上下各留白 20px',
      '细节可参照下图',
    ],
  };
  return (
    <PageHeaderWrapper title={<FormattedMessage id="menu.wineInfo.wineInfoWineEdit" />}>
      <Card>
        <div style={{ display: 'flex' }}>
          <div style={{ flex: 5 }}>
            <Form onFinish={onFinish} ref={form} onFinishFailed={onFinishFailed}>
              <div style={{ marginLeft: 48 }}>
                <Form.Item
                  label={
                    <span className={styles.label}>
                      <FormattedMessage id="wine.wineBottlePicture" />
                      <span>（<FormattedMessage id="wine.wineBottlePictureNote" />）</span>
                    </span>
                  }
                  rules={[{ required: true, message: '请上传酒品logo' }]}
                  name="wineLabelUrl"
                  {...formItemLayout}
                >
                  <Upload
                    style={{ height: 112, display: 'inline-block' }}
                    accept="image/*"
                    name="file"
                    listType="picture-card"
                    className="avatar-uploader"
                    action={Config.UPLOAD_SERVER_HOME}
                    fileList={pictures}
                    // beforeUpload={beforeUpload}
                    onChange={handleChange}
                    onPreview={handlePreview}
                  >
                    {!(pictures && pictures.length > 0) && uploadButton}
                  </Upload>
                </Form.Item>
                <Form.Item
                  label={
                    <span className={styles.label}>
                      <FormattedMessage id="wine.wineCnName" />
                      <span style={{ color: '#999' }}>（<FormattedMessage id="wine.wineNameBoth" />）</span>
                    </span>
                  }
                  {...formItemLayout}
                  name="nameCn"
                  // rules={[{ required: checkNickNameCn, message: '请输入酒品名称中文' }]}
                >
                  <Input
                    style={inputStyle}
                    placeholder="请输入酒品名称中文"
                    onChange={(v) => {
                      if (v.target.value.length > 0) {
                        setCheckNickNameEn(false);
                        return;
                      }
                      setCheckNickNameEn(true);
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineEnName" /></span>}
                  {...formItemLayout}
                  name="nameEn"
                  // rules={[{ required: checkNickNameEn, message: '请输入酒品名称英文' }]}
                >
                  <Input
                    style={inputStyle}
                    placeholder="请输入酒品名称英文"
                    onChange={(v) => {
                      if (v.target.value.length > 0) {
                        setCheckNickNameCn(false);
                        return;
                      }
                      setCheckNickNameCn(true);
                    }}
                  />
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineType" /></span>}
                  {...formItemLayout}
                  name="type"
                  rules={[{ required: true, message: '请输入类型' }]}
                >
                  {/* <Input style={inputStyle} placeholder="请输入类型" /> */}
                  <Select style={inputStyle} placeholder="请选择酒品类型">
                    {E.Type.map((item, index) => {
                      return (
                        <Select.Option
                          key={index}
                          value={`${item.type}/${item.typeEn}`}
                        >{`${item.type}/${item.typeEn}`}</Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineRegion" /></span>}
                  {...formItemLayout}
                  name="region"
                  rules={[{ required: true, message: '请输入产区' }]}
                >
                  {/* <Input style={inputStyle} placeholder="请输入产区" /> */}
                  <Select style={inputStyle} placeholder="请选择产区">
                    {E.Region.map((item, index) => {
                      return (
                        <Select.Option value={`${item.region}/${item.regionEn}`} key={index}>
                          {`${item.region}/${item.regionEn}`}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineDenomination" /></span>}
                  {...formItemLayout}
                  name="level"
                  rules={[{ required: true, message: '请输入级别' }]}
                >
                  {/* <Input style={inputStyle} placeholder="请输入级别" /> */}
                  <Select placeholder="请选择酒品级别" style={inputStyle}>
                    {E.Level.map((item, index) => {
                      return (
                        <Select.Option value={item} key={index}>
                          {item}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                {/* <Form.Item
                  label={<span className={styles.label}>年份</span>}
                  {...formItemLayout}
                  name="vintage"
                  rules={[{ required: true, message: '请输入年份' }]}
                >
                  <DatePicker
                    placeholder="请输入年份"
                    style={inputStyle}
                    disabledDate={(current) => {
                      // console.log(moment().endOf('year'), current, 'cccccccccc');
                      return current && current > moment().add(-1, 'y').endOf('year');
                    }}
                    format={'YYYY'}
                    picker="year"
                  />
                </Form.Item> */}
                <Form.Item
                  label={
                    <span className={styles.label}>
                      <FormattedMessage id="wine.wineVintage" />
                      <span style={{ color: '#999' }}>（ 仅可输入四位数字或NV ）</span>
                    </span>
                  }
                  {...formItemLayout}
                  name="vintage"
                  rules={[
                    {
                      required: true,
                      pattern: /^(19|20)\d{2}|nv|NV$/,
                      message: '请输入正确的年份',
                    },
                  ]}
                >
                  <Input style={inputStyle} placeholder="请输入年份" />
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineAlcohol" /></span>}
                  {...formItemLayout}
                  name="alcohol"
                  rules={[{ required: true, message: '请输入酒精度' }]}
                >
                  <Input style={inputStyle} placeholder="请输入酒精度" addonAfter="％" />
                  {/* <div>
                    <span
                      style={{
                        position: 'relative',
                        marginLeft: 8,
                        lineHeight: '29px',
                        fontSize: 18,
                        top: 1,
                      }}
                    >
                      ％
                    </span>
                  </div> */}
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineGrapeVarieties" /></span>}
                  {...formItemLayout}
                  name="variety"
                  rules={[{ required: true, message: '请输入葡萄品种' }]}
                >
                  <Input style={inputStyle} placeholder="请输入葡萄品种" />
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineAnnualProduction" /></span>}
                  {...formItemLayout}
                  name="annualOutput"
                  // rules={[{ required: true, message: '请输入展年产量' }]}
                >
                  <Input style={inputStyle} placeholder="请输入年产量" addonAfter={<FormattedMessage id="wine.wineUnit" />} />
                  {/* <span>瓶</span> */}
                  {/* <span
                    style={{
                      position: 'relative',
                      marginLeft: 8,
                      lineHeight: '29px',
                      fontSize: 18,
                      top: 1,
                    }}
                  >
                    瓶
                  </span>
                  <div></div> */}
                </Form.Item>
                <Form.Item
                  label={<span className={styles.label}><FormattedMessage id="wine.wineAwards" /></span>}
                  {...formItemLayout}
                  name="awards"
                  // rules={[{ required: true, message: '请输入获奖情况' }]}
                >
                  <Input style={inputStyle} placeholder="请输入获奖情况" />
                </Form.Item>
                {currentUser.type !== 1 && (
                  <Form.Item>
                    <Button
                      onClick={() => {
                        dispatch(routerRedux.push(`/wineInfo/WineInfoList`));
                      }}
                    >
                      <FormattedMessage id="app.cancel" />
                    </Button>
                    <Button
                      type="primary"
                      htmlType="submit"
                      style={{ marginLeft: 20 }}
                      loading={submitLoding}
                    >
                      <FormattedMessage id="app.save" />
                    </Button>
                  </Form.Item>
                )}
              </div>
            </Form>
            <Modal visible={showModal} footer={false} title="image" onCancel={modalOnCancel}>
              <img alt="example" style={{ width: '100%' }} src={imageUrl} />
            </Modal>
          </div>
          <div style={{ flex: 5, display: 'flex' }}>
            <Divider className={styles.line} orientation="center" type="vertical" />
            <ShowInfo showInfoData={showInfoData} style={{ marginLeft: '68px' }} />
          </div>
        </div>
      </Card>
    </PageHeaderWrapper>
  );
}

export default connect(({ wineInfo, user }) => {
  return {
    wineInfo: wineInfo.wineInfo,
    currentUser: user.currentUser,
    submitLoding: wineInfo.submitLoding,
    updata: wineInfo.updata,
  };
})(WineEdit);
